package com.bootdo.clouddo.core.security;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AjaxAuthenticationSuccessHandler implements
		AuthenticationSuccessHandler {
	
	private AjaxSuccessLoginPreHandler handler;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication au) throws IOException,
			ServletException {
		Object userOrSomeThing = au.getPrincipal();
		if(handler != null){
			handler.handler(userOrSomeThing, request, response);
		}
		
		ObjectMapper objectMapper = new ObjectMapper();  
        response.setHeader("Content-Type", "application/json;charset=UTF-8");  
        JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(response.getOutputStream(),  
                JsonEncoding.UTF8);  
        try {  
            objectMapper.writeValue(jsonGenerator, userOrSomeThing);  
        } catch (JsonProcessingException ex) {  
            throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);  
        }  
	}

	public void setHandler(AjaxSuccessLoginPreHandler handler) {
		this.handler = handler;
	}

	
}
